package com.wx.interceptor;

import com.wx.entity.SysSubscribeUser;
import com.wx.exception.BusinessException;
import com.wx.service.SysSubscribeUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>Title:      WxUserInterceptor. </p>
 * <p>Description 微信用户拦截器 </p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company:     陕西天璇信息科技有限公司</p>
 *`
 * @author         <a href="xinglinglove1029@163.com"/>杨文生</a>
 * @since      2019/9/26 18:33
 */
@Slf4j
@Component
public class WxUserInterceptor implements HandlerInterceptor {


	private static final String OPTIONS = "OPTIONS";

	/**
	 * openId
	 */
	private static final String OPEN_ID = "openId";

	@Resource
	private SysSubscribeUserService sysSubscribeUserService;


	/**
	 * After completion.
	 *
	 * @param request  the request
	 * @param response the response
	 * @param arg2     the arg 2
	 * @param ex       the ex
	 *
	 * @throws Exception the exception
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception ex) throws Exception {
		if (ex != null) {
			log.error("<== afterCompletion - 解析token失败. ex={}", ex.getMessage(), ex);
			this.handleException(response);
		}
		WxUserThreadLocal.remove();
	}

	/**
	 * Post handle.
	 *
	 * @param request  the request
	 * @param response the response
	 * @param arg2     the arg 2
	 * @param mv       the mv
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView mv) {
	}

	/**
	 * Pre handle boolean.
	 *
	 * @param request  the request
	 * @param response the response
	 * @param handler  the handler
	 *
	 * @return the boolean
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String uri = request.getRequestURI();
		log.info("<== preHandle - 权限拦截器.  url={}", uri);
		log.info("<== preHandle - 调试模式不走认证.  OPTIONS={}", request.getMethod().toUpperCase());

		if (OPTIONS.equalsIgnoreCase(request.getMethod())) {
			log.info("<== preHandle - 调试模式不走认证.  url={}", uri);
			return true;
		}
		String openId = request.getHeader(OPEN_ID);

		log.info("<== preHandle - 权限拦截器.  openId={}", openId);
		if(StringUtils.isEmpty(openId)){
			throw new BusinessException("header中的openId不能为空");
		}
		SysSubscribeUser sysSubscribeUser = sysSubscribeUserService.selectByOpenId(openId);
		if(sysSubscribeUser == null){
			throw new BusinessException("openId不合法");
		}
		WxOAuth2UserInfo wxOAuth2UserInfo = new WxOAuth2UserInfo();
		wxOAuth2UserInfo.setOpenid(openId);
		wxOAuth2UserInfo.setNickname(sysSubscribeUser.getNickName());
		wxOAuth2UserInfo.setHeadImgUrl(sysSubscribeUser.getHeadImgUrl());
		wxOAuth2UserInfo.setSex(sysSubscribeUser.getSex());
		wxOAuth2UserInfo.setProvince(sysSubscribeUser.getProvince());
		wxOAuth2UserInfo.setCity(sysSubscribeUser.getCity());
		WxUserThreadLocal.set(wxOAuth2UserInfo);
		log.info("<== 用户{},{}权限验证通过", openId, sysSubscribeUser.getNickName());
		return true;
	}

	private void handleException(HttpServletResponse res) throws IOException {
		res.resetBuffer();
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Credentials", "true");
		res.setContentType("application/json");
		res.setCharacterEncoding("UTF-8");
		res.getWriter().write("{\"code\":100009 ,\"message\" :\"解析token失败\"}");
		res.flushBuffer();
	}

}
  